package com.hymjweb.demo.hymj.customer_manage.contact.service;

import com.hymjweb.demo.SpringAopUtil;
import com.hymjweb.demo.framework.sys.BaseService;
import com.hymjweb.demo.framework.sys.SysConstant;
import com.hymjweb.demo.framework.util.DataTypeUtil;
import com.hymjweb.demo.framework.util.PinyinUtil;
import com.hymjweb.demo.hymj.customer_manage.contact.bean.BCustomerContactPojo;
import com.hymjweb.demo.hymj.customer_manage.contact.mapper.BCustomerContactMapper;
import com.hymjweb.demo.hymj.log_manage.aop.annotation.OperationLogger;
import com.hymjweb.demo.hymj.native_bill_manage.bean.BNativeBillPojo;
import com.hymjweb.demo.hymj.native_bill_manage.service.BNativeBillService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class BCustomerContactService extends BaseService {
    @Autowired
    private BCustomerContactMapper bCustomerContactMapper;

    @Autowired
    private BNativeBillService bNativeBillService;

    public List<BCustomerContactPojo> findByBCustomerId(String bCustomerId) {
        List<BCustomerContactPojo> list = bCustomerContactMapper.findByBCustomerId(bCustomerId);
        return list;
    }

    //@OperationLogger(oper = SysConstant.OPER_ADD, operTitle="客户联系人-添加" , operMemo = "", classType =  BCustomerContactPojo.class)
    @Transactional(rollbackFor = {Exception.class})
    public int saveInsert(BCustomerContactPojo pojo) throws Exception {
        if(pojo==null){
            throwException("客户联系人添加参数错误!");
        }
        return bCustomerContactMapper.insert(pojo);
    }


    @OperationLogger(oper = SysConstant.OPER_UPDATE, operTitle="客户联系人-更新" , operMemo = "", classType =  BCustomerContactPojo.class)
    @Transactional(rollbackFor = {Exception.class})
    public int saveUpdate(BCustomerContactPojo pojo) throws Exception {
        if(pojo==null){
            throwException("客户联系人更新参数错误!");
        }
        pojo.setUpdateUserId(this.getLoginCzyId());
        pojo.setUpdateTime(this.getSysTime());
        return bCustomerContactMapper.update(pojo);
    }

    @Transactional(rollbackFor = {Exception.class})
    public int batchInsert(List<BCustomerContactPojo> contactPojoList) throws Exception {
        if(contactPojoList==null || contactPojoList.isEmpty()){
            throwException("批量添加客户联系人参数错误!");
        }

        int affectRows =0 ;
        for(BCustomerContactPojo pojo : contactPojoList){
            affectRows += SpringAopUtil.getBean(this.getClass()).saveInsert(pojo);
        }
        return affectRows;
    }

    @Transactional(rollbackFor = {Exception.class})
    public int insert(BCustomerContactPojo pojo) throws Exception{
        if(pojo == null){
            throwException("添加客户联系人参数错误!");
        }
        DataTypeUtil.isEmptyStrThenThrow(pojo.getCustomerId(), SysConstant.XT_DIC_ERROR_MSG.no_id.getName());
        if(DataTypeUtil.isEmptyStr(pojo.getName())){
            throw new Exception(SysConstant.XT_DIC_ERROR_MSG.no_name.getName());
        }
        if(DataTypeUtil.isEmptyStr(pojo.getPhone())){
            throw new Exception(SysConstant.XT_DIC_ERROR_MSG.no_phone.getName());
        }

        BCustomerContactPojo bCustomerContactPojo = findUK(pojo.getPhone(),pojo.getCustomerId(),null);
        if(bCustomerContactPojo != null){
            throw new Exception(SysConstant.XT_DIC_ERROR_MSG.exist_phone.getName());
        }
        pojo.setId(getSysStrId());
        pojo.setFullPinyin(PinyinUtil.getPinYinALL(pojo.getName(),4));
        pojo.setCamelCharPinyin(PinyinUtil.getPinYinFirst(pojo.getName()));
        pojo.setCreateTime(this.getSysTime());
        pojo.setCreateUserId(this.getLoginCzyId());
        pojo.setUpdateTime(this.getSysTime());
        pojo.setUpdateUserId(this.getLoginCzyId());

        int affectRows = SpringAopUtil.getBean(this.getClass()).saveInsert(pojo);
        return affectRows;
    }

    // @OperationLogger(oper = SysConstant.OPER_DELETE, operTitle="客户联系人-删除" , operMemo = "", classType =  BCustomerContactPojo.class)
    @Transactional(rollbackFor = {Exception.class})
    public int delete(String id) throws Exception{
        if(DataTypeUtil.isEmptyStr(id)){
            throw new Exception("客户联系人删除参数错误!");
        }
        int affectRows = bCustomerContactMapper.delete(id);
        return affectRows;
    }

    public BCustomerContactPojo findUK(String phone, String bCustomerId, String exceptId){
        BCustomerContactPojo bCustomerContactPojo = bCustomerContactMapper.findUK(phone,bCustomerId,exceptId);
        return bCustomerContactPojo;
    }

    /**
     * 根据条件查询联系人
     * @param customerId
     * @return
     */
    public List<BCustomerContactPojo> queryContactByCustomerId(String customerId) {
        if(customerId!=null){
            return bCustomerContactMapper.findByBCustomerId(customerId);
        }
        return null;
    }

    public Object checkUsed(BCustomerContactPojo bCustomerContactPojo) {

        String customerId = bCustomerContactPojo.getCustomerId();
        String name = bCustomerContactPojo.getName();
        String phone = bCustomerContactPojo.getPhone();

        if(customerId!=null && name!=null && phone!=null){
            BCustomerContactPojo pojo = bCustomerContactMapper.queryByUk(customerId,name,phone);
            if(pojo!=null){
                String constactId = pojo.getId();
                Map<String,Object> map = new HashMap<>();
                map.put("keyDeliveryCustomerContactId",constactId);
                List<BNativeBillPojo> bNativeBillPojoList = bNativeBillService.getNoPageList(map);
                return bNativeBillPojoList;
            }
        }
        return null;
    }


    /**
     * 批量更新，注意有的需要进行删除,有的更新，有的插入
     * @param contactPojoList
     * @param customerId
     * @return
     */
    public int batchUpdate(List<BCustomerContactPojo> contactPojoList, String customerId) throws Exception {

        if(contactPojoList==null || contactPojoList.isEmpty() || customerId==null){
            return SysConstant.INT_ZERO;
        }

        // 1.根据 customerId 得到更新前的联系人列表
        List<BCustomerContactPojo> updateBeforeContactPojoList = bCustomerContactMapper.findByBCustomerId(customerId);

        // 2.判断是否为 null
        if(updateBeforeContactPojoList == null || updateBeforeContactPojoList.isEmpty()){
            int affectRows = 0;
            // 直接批量插入结束
            for(BCustomerContactPojo pojo : contactPojoList){
                if(DataTypeUtil.isEmptyStr(pojo.getId())){
                    pojo.setId(this.getSysStrId());
                }
                if(DataTypeUtil.isEmptyStr(pojo.getCustomerId())){
                    pojo.setCustomerId(customerId);
                }
                affectRows += SpringAopUtil.getBean(this.getClass()).saveInsert(pojo);
            }
            return affectRows;
        }

        // 3.原来的表中有数据,现当前要插入的数据要进行判断比较，id 相同的则更新
        // 3.1 选择出相同的放到待更新列表中
        List<BCustomerContactPojo> waitUpdateList = new ArrayList<>();
        for(BCustomerContactPojo pojo1 : contactPojoList){
            for(BCustomerContactPojo pojo2 : updateBeforeContactPojoList){
                if(pojo1.getId()!=null && pojo2.getId()!=null && pojo1.getId().equals(pojo2.getId())){
                    waitUpdateList.add(pojo1);
                    break;
                }
            }
        }

        // 3.2 选择出待删除的
        List<BCustomerContactPojo> waitDeleteList = new ArrayList<>();
        for(BCustomerContactPojo pojo2 : updateBeforeContactPojoList){
            boolean isExist = false;
            for(BCustomerContactPojo pojo1 : contactPojoList){
                if(pojo1.getId()!=null && pojo2.getId()!=null && pojo1.getId().equals(pojo2.getId())){
                    isExist = true;
                    break;
                }
            }
            if(!isExist){
                waitDeleteList.add(pojo2);
            }
        }

        // 3.3 选择出待增加的
        List<BCustomerContactPojo> waitInsertList = new ArrayList<>();
        for(BCustomerContactPojo pojo1 : contactPojoList){
            boolean isExist = false;
            for(BCustomerContactPojo pojo2 : updateBeforeContactPojoList){
                if(pojo1.getId()!=null && pojo2.getId()!=null && pojo1.getId().equals(pojo2.getId())){
                    isExist = true;
                    break;
                }
            }
            if(!isExist){
                waitInsertList.add(pojo1);
            }
        }

        int updateRows = 0;
        int deleteRows = 0;
        int insertRows = 0;
        // 待更新的列表有数据
        if(!waitUpdateList.isEmpty()){
            for(BCustomerContactPojo pojo : waitUpdateList){
                updateRows += SpringAopUtil.getBean(this.getClass()).saveUpdate(pojo);
            }
        }

        if(!waitDeleteList.isEmpty()){
            for(BCustomerContactPojo pojo : waitDeleteList){
                deleteRows += SpringAopUtil.getBean(this.getClass()).delete(pojo.getId());
            }
        }

        if(!waitInsertList.isEmpty()){
            for(BCustomerContactPojo pojo : waitInsertList){
                insertRows += SpringAopUtil.getBean(this.getClass()).saveInsert(pojo);
            }
        }

        return updateRows + deleteRows + insertRows;
    }
}
